package com.testapp.supers.app;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smartrefresh.header.DeliveryHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.testapp.supers.app.bean.DataBean;
import com.testapp.supers.app.utils.DensityUtils;
import com.testapp.supers.app.view.MyDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class Alamfragment extends Fragment implements OnRefreshListener {
    //弹出的dialog的控件
    private ImageView iv_close;
    private RelativeLayout rl_add;
    private RecyclerView rv;
    private SmartRefreshLayout srl;
    //假数据
    private List<DataBean> data;
    CheckAdapter mAdapter;
    private static final String ARG_SHOW_TEXT = "text";

    private String mContentText;
    private View rootView;
    //弹窗
    MyDialog addDepartmentDialog;
    private SweetAlertDialog sweetAlertDialog;
    private TextView title1;
    private DataBean dataBean1;
    private TextView content;
    private TextView addr;
    private TextView grade;
    private TextView time;
    private TextView up;
    private TextView state;
    private int mPosition;

    public Alamfragment() {
    }

    public static Alamfragment newInstance(String param1) {
        Alamfragment fragment = new Alamfragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHOW_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mContentText = getArguments().getString(ARG_SHOW_TEXT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_alamfragment, container, false);
        initView();
        return rootView;
    }

    // fragment所在的activity创建完成
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    public void initView() {
        rv = rootView.findViewById(R.id.rv_employee);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        srl = rootView.findViewById(R.id.srl_employee);
        srl.setRefreshHeader(new DeliveryHeader(getActivity()));
        srl.setOnRefreshListener(this);
        initAdapter();
    }

    public void initData() {
        data = new ArrayList<>();
        //模拟数据1
        DataBean dataBean = new DataBean();
        dataBean.setAddr("桂林象鼻山东半区监测点");
        dataBean.setContent("由于近段时间连续强降雨，导致象鼻山东半区边坡倾斜率骤升，极有可能出现山体滑坡事故，请相关部门提前采取措施！");
        dataBean.setGrade("三级");
        dataBean.setState("未上报");
        dataBean.setTitle("山体倾斜率预警！！");
        dataBean.setTime("2019-03-20 14:41:39");
        dataBean.setUp("桂林市气象局");
        data.add(dataBean);
        //模拟数据2
        dataBean = new DataBean();
        dataBean.setAddr("贵州九寨沟监测点");
        dataBean.setContent("由于近段时间连续强降雨，导致九寨沟地区环境水位骤升，极有可能出现洪涝事故，请相关部门提前采取措施！");
        dataBean.setGrade("二级");
        dataBean.setState("未上报");
        dataBean.setTitle("洪涝红色预警！！");
        dataBean.setTime("2019-03-20 14:41:39");
        dataBean.setUp("贵州省气象局");
        data.add(dataBean);
        //模拟数据3
        dataBean = new DataBean();
        dataBean.setAddr("贵州九寨沟监测点");
        dataBean.setContent("由于近段时间连续强降雨，导致九寨沟地区环境水位骤升，极有可能出现洪涝事故，请相关部门提前采取措施！");
        dataBean.setGrade("二级");
        dataBean.setState("已上报");
        dataBean.setTitle("土壤含水量橙色色预警！！");
        dataBean.setTime("2019-03-20 14:41:39");
        dataBean.setUp("贵州省气象局");
        data.add(dataBean);
        //模拟数据4
        dataBean = new DataBean();
        dataBean.setAddr("百色山区监测点");
        dataBean.setContent("由于近段时间连续强降雨，导致百色地区环境水位骤升，极有可能出现山体滑坡事故，请相关部门提前采取措施！");
        dataBean.setGrade("三级");
        dataBean.setState("正在处理");
        dataBean.setTitle("环境雨量红色预警！！");
        dataBean.setTime("2019-03-20 14:41:39");
        dataBean.setUp("贵州省气象局");
        data.add(dataBean);
        //模拟数据5
        dataBean = new DataBean();
        dataBean.setAddr("百色大王岭监测点");
        dataBean.setContent("由于近段时间连续强降雨，导致九寨沟地区环境水位骤升，极有可能出现洪涝事故，请相关部门提前采取措施！");
        dataBean.setGrade("一级");
        dataBean.setState("已处理");
        dataBean.setTitle("土壤松弛白色预警！！");
        dataBean.setTime("2019-03-20 14:41:39");
        dataBean.setUp("百色气象局");
        data.add(dataBean);


        srl.autoRefresh();
    }

    public class CheckAdapter extends BaseQuickAdapter<DataBean, BaseViewHolder> {

        private CheckAdapter() {
            super(R.layout.item_check);
        }

        @Override
        protected void convert(BaseViewHolder helper, DataBean item) {
            helper.setText(R.id.title, item.getTitle());
            helper.setText(R.id.tv_grade, item.getGrade());
            helper.setText(R.id.tv_state, item.getState());
            helper.addOnClickListener(R.id.rl_supervisor);
        }
    }

    private void initAdapter() {
        mAdapter = new CheckAdapter();
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.rv_divider));
        rv.addItemDecoration(divider);
        rv.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                int itemViewId = view.getId();
                switch (itemViewId) {
                    case R.id.rl_supervisor:
                        mPosition = position;
                        dataBean1 = data.get(position);
                        showSetSupervisorDialog();
                        break;
                }
            }
        });
        rv.setAdapter(mAdapter);
    }

    //显示详情Dialog
    private void showSetSupervisorDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_set_supervisor, null);
        addDepartmentDialog = new MyDialog(getActivity(), 0, 0, dialogView, R.style.DialogTheme);
        addDepartmentDialog.setCancelable(false);
//                      设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = addDepartmentDialog.getWindow();
        lp.copyFrom(window.getAttributes());
//                        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//                        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = DensityUtils.dp2px(getActivity(), 340);
        lp.height = DensityUtils.dp2px(getActivity(), 500);
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        initDialogView(dialogView);
        initDialogListener();
        addDepartmentDialog.show();
        window.setAttributes(lp);
    }

    private void initDialogView(View view) {
        iv_close = (ImageView) view.findViewById(R.id.iv_close);
        title1 = (TextView) view.findViewById(R.id.title1);
        title1.setText(String.format(getString(R.string.title1), dataBean1.getTitle()));
        content = (TextView) view.findViewById(R.id.content);
        content.setText(String.format(getString(R.string.content), dataBean1.getContent()));
        addr = (TextView) view.findViewById(R.id.addr);
        addr.setText(String.format(getString(R.string.addr), dataBean1.getAddr()));
        grade = (TextView) view.findViewById(R.id.grade);
        grade.setText(String.format(getString(R.string.grade), dataBean1.getGrade()));
        time = (TextView) view.findViewById(R.id.time);
        time.setText(String.format(getString(R.string.time), dataBean1.getTime()));
        up = (TextView) view.findViewById(R.id.up);
        up.setText(String.format(getString(R.string.up), dataBean1.getUp()));
        state = (TextView) view.findViewById(R.id.state);
        state.setText(String.format(getString(R.string.state), dataBean1.getState()));
        rl_add = (RelativeLayout) view.findViewById(R.id.rl_add);


    }

    private void initDialogListener() {
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addDepartmentDialog.dismiss();
            }
        });
        rl_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sweetAlertDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE);
                sweetAlertDialog.setTitleText("确认上报上级?")
                        .setContentText("上报后,上级将会收到通知，并由上级处理该警报，处理后再回馈到app!")
                        .setCancelText("取消")
                        .setConfirmText("确认")
                        .showCancelButton(true)
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.dismiss();

                            }
                        })
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(final SweetAlertDialog sDialog) {
                                sDialog.setTitleText("正在上报")
                                        .setContentText("")
                                        .showCancelButton(false)
                                        .setCancelClickListener(null)
                                        .setConfirmClickListener(null)
                                        .changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        sDialog.setTitleText("上报成功")
                                                .setContentText("")
                                                .showCancelButton(false)
                                                .setCancelClickListener(null)
                                                .setConfirmClickListener(null)
                                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                data.get(mPosition).setState("已上报");
                                                sDialog.dismiss();
                                                addDepartmentDialog.dismiss();
                                                srl.autoRefresh();
                                                ToastUtils.showLong("已将险情上报领导，等待上级处理并回馈");
                                            }
                                        }, 1000);
                                    }
                                }, 1000);
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        updateCheck(data);
    }

    public void updateCheck(List<DataBean> data) {
        System.out.println("setNewData");
//        System.out.println(data.get(0));
        mAdapter.setNewData(data);

        //空布局
        View nodataview = getLayoutInflater().inflate(R.layout.nodata, null);
        // 没有数据的时候默认显示该布局
        mAdapter.setEmptyView(nodataview);
//        mAdapter.loadMoreComplete();
//        mAdapter.notifyDataSetChanged();
        srl.finishRefresh();
    }
}
